package com.example.demo01.utils;

import com.example.demo01.entity.Result;
import com.example.demo01.service.IClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Component
public class FileUploadUtils {

    // 头像保存路径
    @Value("${file.avatarPath}")
    private String avatarPath;

    @Autowired
    private IClassService iClassService;

    /**
     * 上传头像
     * @param file 头像文件
     * @return 头像访问URL
     */
    public Result uploadAvatar(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("上传失败，请选择文件");
        }

        // 获取项目根目录
        String projectPath = System.getProperty("user.dir");
        // 头像存储的完整路径
        String avatarDir = projectPath + File.separator + avatarPath;

        // 确保目录存在
        File dir = new File(avatarDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        // 保存文件
        try {
            file.transferTo(new File(avatarDir + File.separator + fileName));
            System.out.println(avatarDir + File.separator + fileName);
            // 返回访问URL
            String fileUrl = "/avatar/" + fileName;
            return Result.success(fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败：" + e.getMessage());
        }
    }


}
